// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"flag"
	"fmt"
	"net"
	"net/http"
	"os"
	"runtime"
	"time"

	cfg "ycx-config"
	log "ycx-glog"

	"chat/common"
	"chat/db"
)

var addr = flag.String("addr", ":8080", "http service address")

func serveHome(w http.ResponseWriter, r *http.Request) {
	log.Infoln(r.URL)
	if r.URL.Path != "/" {
		http.Error(w, "Not found", http.StatusNotFound)
		return
	}
	if r.Method != "GET" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}
	http.ServeFile(w, r, "home.html")
}

func config() {
	/************ 加载日志模块 ************/
	// 日志目录
	logDir := common.EnsureDir("./_glog/" + log.LogDirName())
	if runtime.GOOS == "windows" {
		flag.Set("alsologtostderr", "true")
	} else {
		flag.Set("alsologtostderr", "false")
		// 记录严重错误(仅linux有效)
		common.RecordFatal(fmt.Sprintf("./_log/fatal_%s.log", common.TimeFormat(time.Now(), "yyyyMMdd_HHmmss")))
	}
	flag.Set("log_dir", logDir)
	flag.Set("v", "3")
	flag.Parse()

	log.MaxSize = 1024 * 1024 * 10 //10M
	log.DirMaxSize = log.MaxSize * 100
	defer log.Flush()
	go func() {
		for {
			time.Sleep(2 * 1e9)
			log.Flush()
		}
	}()
}

func dbconfig() {
	_, _, err := db.InitDB(cfg.String("driver"), cfg.String("data_source"), cfg.String("cache_leveldb"))
	if err != nil {
		log.Errorln(err)
	} else {
		log.Infoln("InitDB return success")
	}
}

func main() {
	/************ 加载配置模块 ************/
	cfg.LoadConfig(common.GetAbsolutePath("./default.conf"), "json")
	cfg.AutoSaveConfig()
	go func() {
		for {
			time.Sleep(1 * 1e9)
			cfg.ResetLoad()
		}
	}()

	// 日志初始化
	config()

	// 数据库初始化
	dbconfig()

	/************ udp ************/
	udp_addr, err := net.ResolveUDPAddr("udp", ":8366")
	checkError(err)

	conn, err := net.ListenUDP("udp", udp_addr)
	defer conn.Close()
	if err != nil {
		log.Infoln("Error: %s", err.Error())
		os.Exit(1)
	}
	//	serveUdp(conn)

	//********** websocket *************/
	flag.Parse()
	hub := newHub()
	go hub.run()

	http.HandleFunc("/", serveHome)
	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		serveWs(hub, w, r, conn)
	})
	err2 := http.ListenAndServe(*addr, nil)
	if err2 != nil {
		log.Fatal("ListenAndServe: ", err2)
	}
}
